import axios from 'axios';
import router from '../router/index';
import store from '../store/index';
// import Vue from '@/main'
import base from './api/base.js'; // 导入接口域名列表

/**
 * 请求失败后的错误统一处理
 * @param {Number} status 请求失败的状态码
 */
const errorHandle = (status, other) => {
  // 状态码判断
  switch (status) {
    // 401: 未登录状态，跳转登录页
    case 401:
      break;
      // 403 token过期
      // 清除token并跳转登录页
    case 403:
      break;
      // 404请求不存在
    case 404:
      break;
    default:
      console.log(other);
  }
}

// 创建axios实例
let instance = axios.create({ timeout: 1000 * 12 });

//请求拦截器
instance.interceptors.request.use(config => {
  console.log(config.url)
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  console.log(window.sessionStorage.getItem('tk'))
  if (!window.sessionStorage.getItem('tk')) {
    initToken()
  }
  config.params = {
    ...config.params,
    tk: window.sessionStorage.getItem('tk')
  }
  console.log(config.params )
  return config
})

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  res => {
    if (res.status === 200) {
      return Promise.resolve(res.data)
    } else {
      return Promise.reject(res.data)
    }
  },
  // 请求失败
  error => {
    console.log(error);
  }
);
const queryinfo = {
  username: "scjzy",
  pwd: "123456",
  action: "token"
}

async function initToken() {
  const {data: {result:res}} = await axios.get(`${base.torch}/curl/save`, { params: queryinfo })
  console.log(res.data);
  window.sessionStorage.setItem('tk',res.data)

}

export default instance;
